<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="车道名称">
          <el-input v-model="queryParams.laneName" placeholder="请输入车道名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="queryParams.lotId" placeholder="请选择停车场" clearable size="small">
            <el-option v-for="item in parkingLotOptions" :key="item.lotId" :label="item.lotName" :value="item.lotId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
          <el-button type="success" size="small" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="laneList" border style="width: 100%">
      <el-table-column label="车道名称" prop="laneName" />
      <el-table-column label="车道编码" prop="laneCode" />
      <el-table-column label="所属停车场" prop="lotName" />
      <el-table-column label="车道类型" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.laneType === '1' ? 'success' : 'warning'">
            {{ scope.row.laneType === '1' ? '入口' : '出口' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="二维码" prop="qrCode" show-overflow-tooltip />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleBindQR(scope.row)">绑定二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格下方添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车道名称" prop="laneName">
          <el-input v-model="form.laneName" placeholder="请输入车道名称" />
        </el-form-item>
        <el-form-item label="车道编码" prop="laneCode">
          <el-input v-model="form.laneCode" placeholder="请输入车道编码" />
        </el-form-item>
        <el-form-item label="停车场" prop="lotId">
          <el-select v-model="form.lotId" placeholder="请选择停车场">
            <el-option v-for="item in parkingLotOptions" :key="item.lotId" :label="item.lotName" :value="item.lotId" />
          </el-select>
        </el-form-item>
        <el-form-item label="车道类型" prop="laneType">
          <el-radio-group v-model="form.laneType">
            <el-radio label="1">入口</el-radio>
            <el-radio label="2">出口</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 绑定二维码对话框 -->
    <el-dialog title="绑定二维码" :visible.sync="qrDialog.visible" width="500px" append-to-body>
      <el-form ref="qrForm" :model="qrForm" label-width="80px">
        <el-form-item label="二维码" prop="qrCode">
          <el-input v-model="qrForm.qrCode" placeholder="请输入二维码链接">
            <template slot="append">
              <el-button type="primary" @click="generateQRCode">生成二维码</el-button>
            </template>
          </el-input>
        </el-form-item>
        <!-- 添加二维码图片预览 -->
        <el-form-item v-if="qrForm.qrCode">
          <div class="qr-preview">
            <img :src="qrForm.qrCode" alt="二维码预览" class="qr-image">
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitQRForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLane, addLane, updateLane, bindQR } from '@/api/parkinglotmanagement/lane'
import { getLotById } from '@/api/parkinglotmanagement/parking'

export default {
  name: 'LaneManagement',
  data() {
    return {
      // 修改查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        laneName: '',
        lotId: undefined
      },
      // 添加分页数据
      pagination: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      // 加载标识
      loading: false,
      // 车道列表
      laneList: [],
      // 停车场选项
      parkingLotOptions: [],
      // 弹窗控制
      dialog: {
        title: '',
        visible: false
      },
      // 表单对象
      form: {
        laneId: undefined,
        laneName: '',
        laneCode: '',
        lotId: undefined,
        laneType: '1',
        status: '0',
      },
      // 表单校验规则
      rules: {
        laneName: [
          { required: true, message: '请输入车道名称', trigger: 'blur' }
        ],
        laneCode: [
          { required: true, message: '请输入车道编码', trigger: 'blur' }
        ],
        lotId: [
          { required: true, message: '请选择停车场', trigger: 'change' }
        ],
        laneType: [
          { required: true, message: '请选择车道类型', trigger: 'change' }
        ]
      },
      // 二维码弹窗
      qrDialog: {
        visible: false
      },
      // 二维码表单
      qrForm: {
        laneId: undefined,
        qrCode: ''
      }
    }
  },
  created() {
    this.getParkingLots()
    this.getLaneList()
  },
  methods: {
    // 获取停车场列表
    getParkingLots() {
      // TODO: 调用获取停车场列表接口
      getLotById().then(res => {
        this.parkingLotOptions = res.data
      })
    },
    // 获取车道列表
    async getLaneList() {
      this.loading = true
      try {
        const response = await listLane(this.queryParams)
        if (response.code === 200) {  // 假设成功状态码为200
          this.laneList = response.data.records || []
          this.pagination.total = response.data.total
        } else {
          this.$message.error(response.msg || '获取车道列表失败')
        }
      } catch (error) {
        console.error('获取车道列表失败:', error)
        this.$message.error('获取车道列表失败')
      } finally {
        this.loading = false
      }
    },
    // 查询按钮点击
    handleQuery() {
      this.getLaneList()
    },
    // 新增按钮点击
    handleAdd() {
      this.dialog.title = '添加车道'
      this.dialog.visible = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
        this.form = {
          laneId: undefined,
          laneName: '',
          laneCode: '',
          lotId: undefined,
          laneType: '1',
          status: '0',
        }
      })
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.dialog.title = '编辑车道'
      this.dialog.visible = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
        this.form.laneId = row.laneId
        this.form.laneName = row.laneName
        this.form.laneCode = row.laneCode
        this.form.lotId = row.lotId
        this.form.laneType = row.laneType
        this.form.status = row.status
      })
    },
    // 绑定二维码按钮点击
    handleBindQR(row) {
      this.qrDialog.visible = true
      this.qrForm = {
        laneId: row.laneId,
        qrCode: row.qrCode || ''
      }
    },
    // 提交表单
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (this.form.laneId) {
            this.handleUpdate()
          } else {
            this.handleCreate()
          }
        }
      })
    },
    // 新增车道
    async handleCreate() {
      try {
        const response = await addLane(this.form)
        if (response.code === 200) {
          this.$message.success('新增成功')
          this.dialog.visible = false
          this.getLaneList()
        } else {
          this.$message.error(response.msg || '新增失败')
        }
      } catch (error) {
        console.error('新增车道失败:', error)
        this.$message.error('新增失败')
      }
    },
    // 修改车道
    async handleUpdate() {
      try {
        const response = await updateLane(this.form)
        if (response.code === 200) {
          this.$message.success('修改成功')
          this.dialog.visible = false
          this.getLaneList()
        } else {
          this.$message.error(response.msg || '修改失败，请检查输入数据是否正确')
        }
      } catch (error) {
        console.error('修改车道失败:', error)
        this.$message.error(error.response?.data?.msg || '修改失败，请检查网络连接')
      }
    },
    // 提交二维码
    async submitQRForm() {
      try {
        const response = await bindQR(this.qrForm)
        if (response.code === 200) {
          this.$message.success('二维码绑定成功')
          this.qrDialog.visible = false
          this.getLaneList()
        } else {
          this.$message.error(response.msg || '二维码绑定失败')
        }
      } catch (error) {
        console.error('绑定二维码失败:', error)
        this.$message.error('绑定二维码失败')
      }
    },
    // 添加分页处理方法
    handlePageChange(page) {
      this.queryParams.pageNum = page
      this.getLaneList()
    },
    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.queryParams.pageNum = 1
      this.getLaneList()
    },
    // 生成随机二维码
    generateQRCode() {
      // 生成随机字符串作为二维码内容
      const randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
      // 使用在线二维码生成服务
      const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${encodeURIComponent(randomString)}`;
      this.qrForm.qrCode = qrCodeUrl;
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.qr-preview {
  text-align: center;
  margin-top: 10px;
}

.qr-image {
  max-width: 150px;
  max-height: 150px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
